package mongo

import "github.com/globalsign/mgo"

type mongoSession struct {
	*mgo.Session
	ref   int
	index int
}

type sessionHeap []*mongoSession

func (h sessionHeap) Len() int {
	return len(h)
}

func (h sessionHeap) Less(i, j int) bool {
	return h[i].ref < h[j].ref
}

func (h sessionHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
	h[i].index = i
	h[j].index = j
}

// Push push mongodb session
func (h *sessionHeap) Push(s interface{}) {
	s.(*mongoSession).index = len(*h)
	*h = append(*h, s.(*mongoSession))
}

// Pop pop mongodb session
func (h *sessionHeap) Pop() interface{} {
	l := len(*h)
	s := (*h)[l-1]
	s.index = -1
	*h = (*h)[:l-1]
	return s
}
